//
//  HHFMDB1ViewController.m
//  Flower
//
//  Created by 花花 on 2016/12/23.
//  Copyright © 2016年 花花. All rights reserved.
//

//没有封装 直接使用
#import "HHFMDB1ViewController.h"
#import <FMDB.h>

#import "HHAddViewController.h"
#import "HHEditorViewController.h"
@interface HHFMDB1ViewController ()<HHEditorViewControllerDelegate,HHAddViewControllerDelegate>{

NSIndexPath *_indexPath;
}
//存放所有的名字数组
@property(nonatomic, strong) NSMutableArray *nameArr;
//存放所有的号码数组
@property(nonatomic, strong) NSMutableArray *phoneArr;

@property(nonatomic, strong) FMDatabase *database;

@end

@implementation HHFMDB1ViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupNav];
    
    [self setupDB];
}

/*
 sqlite语句 不区分大小写
 */
#pragma mark - setupDB
-(void)setupDB{
    
    // 1.获取数据文件的路径
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath =[path stringByAppendingPathComponent:@"User.sqlite"];
    HHLog(@"%@",filePath);
    //2.得到数据库
    self.database = [FMDatabase databaseWithPath:filePath];
    if ([self.database open]) { //3.打开数据库
        
        HHLog(@"数据库打开成功");
    }
    //4. 创建                name、phone字段  User：表名   TEXT：类型 （比如：integer）
    NSString *createTable = @"CREATE TABLE IF NOT EXISTS User (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,name TEXT,phone TEXT)";

    BOOL is_Table = [self.database executeUpdate:createTable];
    
    if(is_Table){
        HHLog(@"创建表success");
    
    }else{
        HHLog(@"创建表failure");
    }
    //如果一开始不调用的话 则每次进去是空的
    [self selectFrom];

}
#pragma mark - setupNav
-(void)setupNav{
    
    self.navigationItem.rightBarButtonItem =[UIBarButtonItem itemWithImage:@"addressbook" highImage:@"addressbook" target:self action:@selector(addOnClick)];
}
#pragma mark - SEL Method
-(void)addOnClick{
    
    HHAddViewController *addVc =[[HHAddViewController alloc]init];
    addVc.delegate = self;
    [self.navigationController pushViewController:addVc animated:YES];

}


#pragma mark - <UITableViewDataSource,UITableViewDelegate>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 
    return self.nameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (!cell) {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellID"];
    }
    
    cell.textLabel.text = self.nameArr[indexPath.row];
    cell.detailTextLabel.text = self.phoneArr[indexPath.row];
    return cell;
    
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{

    return @"删除";
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    BOOL delete_row =[self.database executeUpdate:@"delete from User WHERE name = ? and phone = ?", self.nameArr[indexPath.row],self.phoneArr[indexPath.row]];

    if (delete_row) {
        HHLog(@"删除一行");
        [self.nameArr removeObjectAtIndex:indexPath.row];
        [self.phoneArr removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _indexPath = indexPath;
    HHEditorViewController *editVc =[[HHEditorViewController alloc]init];
    editVc.name = self.nameArr[indexPath.row];
    editVc.phone = self.phoneArr[indexPath.row];
    editVc.delegate = self;
    [self.navigationController pushViewController:editVc animated:YES];
    
}

#pragma mark - <HHAddViewControllerDelegate>
-(void)addressTextF:(UITextField *)addressText phoneTextF:(UITextField *)phoneTextF{
    
    NSString *insert = @"INSERT INTO User(name,phone)VALUES(?,?)";
    BOOL is_insert = [self.database executeUpdate:insert,addressText.text,phoneTextF.text];
    
    if (is_insert) {
        HHLog(@"插入成功");
        [self selectFrom];
        [self.tableView reloadData];
        
    }else{
        HHLog(@"插入失败");
    
    }

    

}

#pragma mark - <HHEditorViewControllerDelegate>
-(void)editorTextF:(UITextField *)editorText phoneTextF:(UITextField *)phoneTextF{

    HHLog(@"编辑有问题有待完善");

    
    NSString *update =[NSString stringWithFormat:@"UPDATE User SET 'name' = '%@','phone' = '%@';",editorText.text,phoneTextF.text];
    
    BOOL is_update =[self.database executeUpdate:update];
    if (is_update) {
          HHLog(@"更新成功");
        [self selectFrom];
//warning 表面上成功了 但是数据还是全部改成一样的了
        [self.tableView reloadRowsAtIndexPaths:@[_indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        
    }else{
        HHLog(@"更新失败");
    }
}

-(void)selectFrom{
    
    [self.nameArr removeAllObjects];
    [self.phoneArr removeAllObjects];
    NSString *sql = @"select *from User"; //查询整个表
    FMResultSet *result =[self.database executeQuery:sql]; // //根据条件查询
    while (result.next) { // //遍历结果集合
        NSString *userName = [result stringForColumn:@"name"];
        [self.nameArr addObject:userName];
        
        NSString *userPhone =[result stringForColumn:@"phone"];
        [self.phoneArr addObject:userPhone];
    }
    
}

#pragma mark - Setter && Getter
-(NSMutableArray *)nameArr{
    
    if (!_nameArr) {
        _nameArr = [NSMutableArray array];
    }
    
    return _nameArr;
    
}
-(NSMutableArray *)phoneArr{
    
    if (!_phoneArr) {
        _phoneArr = [NSMutableArray array];
    }
    
    return _phoneArr;
    
}
@end
